/** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
**/

var serviceObj = null;
var deviceInfoTimerId = null;

// variables for transaction IDs returned from asyncronous channel calls
var batteryChannel = "";
var signalChannel = "";
var networkChannel = "";

function initSystemServices() {
    try {
        serviceObj = nokia.device.load("sysinfo");
		logDebug("Platform Services initialized okay!");
    } catch (e) {
		logDebug("Platform Services initialization FAILED :(");

		serviceObj = null;
        var error = e.toString();
		Alert.show(str_error + error);
    }
	
	// Platform Services support for synchronous and asynchronous method calls depends on the channel and the method operating on the channel. Only the
	// supported video decoders channel is sync so let's display it right after initialization (if available) and then start monitoring for async
	// channels as well.
	if (serviceObj)	{
		// get the initial values for async channels. The startChannel will trigger on change so we must get the initial values here.
		try {
			logDebug("Getting initial values for async channels...");
	        batteryChannel = serviceObj.getChannel("BatteryLevel", onBatteryNotification, onDeviceInfoError);
	        signalChannel = serviceObj.getChannel("SignalStrength", onSignalNotification, onDeviceInfoError);
	        networkChannel = serviceObj.getChannel("Network", onNetworkNotification, onDeviceInfoError);

			$("#debug_line").removeClass("hidden");
		} catch (e) {
	        var error = e.toString();
			logDebug("Some async channel didn't get the initial values correctly: " + error);
	    }
		// setup async channels; they'll serve you with callbacks on changes. The null parameter is the trigger treshold, if not specified
		// the callback will trigger on every change.
		try {
			logDebug("Start monitoring on async channels...");
	        batteryChannel = serviceObj.startChannel(onBatteryNotification, "BatteryLevel", null, onDeviceInfoError);
	        signalChannel = serviceObj.startChannel(onSignalNotification, "SignalStrength", null, onDeviceInfoError);
	        networkChannel = serviceObj.startChannel(onNetworkNotification, "Network", null, onDeviceInfoError);			

			$("#debug_line").removeClass("hidden");
		} catch (e) {
	        var error = e.toString();
			logDebug("Some async channel didn't get started correctly: " + error);
	    }
		
		// video decoders info is a sync channel but not available on all platforms.
	    try {
			logDebug("Fetching Supported Video Decoders...");
			var channelData = serviceObj.getChannel("SupportedVideoDecoders");
			var supportedDecoders = "";
			for (var i=0; i < channelData.supportedVideoDecoders.length; ++i) {
				supportedDecoders += (", " + channelData.supportedVideoDecoders[i].identifier);
			}
			supportedDecoders = supportedDecoders.slice(1); 
			
	        $("#video_info").removeClass("hidden");
			$("#video_info").html(supportedDecoders);
			$("#debug_line").removeClass("hidden");
	    } catch (e) {
	        var error = e.toString();
			logDebug("Supported Video Decoders information NOT AVAILABLE, silently ignoring... Error: " + error);
	    }
	}
}

function stopChannelMonitoring() {
    try {
		logDebug("Stopping async channels...");
		
        serviceObj.stopChannel("BatteryLevel");
        serviceObj.stopChannel("SignalStrength");
        serviceObj.stopChannel("Network");
    } 
    catch (e) {
        var error = e.toString();
		logDebug("Stopping async channels failed: " + error);
    }
}

//
// callbacks
function onBatteryNotification(channelData) {
    try {
        $("#batt_info").html(channelData.batteryLevel + "%");
    } catch (e) {
        var error = e.toString();
		logDebug("Error reading channel data: " + error);
    }
}
function onNetworkNotification(channelData) {
    try {
		var networkData = channelData.networkName + ", " + channelData.networkMode;
        $("#network_info").html(networkData);
    } catch (e) {
        var error = e.toString();
		logDebug("Error reading channel data: " + error);
    }
}
function onSignalNotification(channelData) {
    try {
        //Note : signalStrength is returned interms of decibels by S60. Approximate conversion is made to get the value in percentage.
        $("#signal_info").html(channelData.signalStrength + "%");
    } catch (e) {
        var error = e.toString();
		logDebug("Error reading channel data: " + error);
    }
}

//
// error handler
function onDeviceInfoError(error) {
	// silently ignore as we don't really need this data
	logDebug("Error reading channel data: " + error.message);
}

